import { Module } from "vuex";
import { getList } from "@/api";
import { RootStore } from "@/store";

interface DictionariesModule {
  dicList: { [propName: string]: Array<unknown> };
}

const store: Module<DictionariesModule, RootStore> = {
  state: {
    dicList: {
      floorList: [],
      roomTypeList: [],
      booleanList: [
        {
          label: "是",
          value: 1,
        },
        {
          label: "否",
          value: 0,
        },
      ],
    },
  },
  getters: {
    getList: (state) => (name: string) => {
      const list = state.dicList[`${name}List`];
      !list &&
        getList({ name }).then(
          (res) => (state.dicList[`${name}List`] = res.data)
        );
      return list;
    },
  },
  mutations: {
    setList(state, payload) {
      const name = `${payload.name}List`;
      state.dicList[name] = payload.data;
    },
  },
  actions: {
    async updateList({ commit }, payload = "") {
      const res = await getList({ name: payload });
      commit("setList", { name: payload, data: res.data });
    },
    async getList({ state, dispatch }, payload = "") {
      const name = `${payload}List`;
      !state.dicList[name]?.length && (await dispatch("updateList", payload));
      return state.dicList[name];
    },
  },
};
export default store;
